﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace YSC_Core.BLL.Domain.Utils
{
    /// <summary>
    /// 模拟请求
    /// </summary>
    public static class HttpUtils
    {
        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="Url">请求地址</param>
        /// <param name="postDataStr">请求数据</param>
        /// <param name="contentType">数据类型</param>
        /// <returns></returns>
        public static string HttpPost(string Url, string postDataStr, string contentType = "application/json")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = contentType;
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }
        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="Url">请求地址</param>
        /// <param name="postDataStr">请求数据</param>
        /// <returns></returns>
        public static string HttpGet(string Url, string postDataStr = "")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.Accept = "application/json";
            request.Headers.Add("Authorization", "D623B6743C56E6A68E19828E74244C3ECB5AC1BDBFEF35309EAA0A15FE017EF59367E5AA5D3AE1E02B7C000C8FCFB6DB52B3D0784AB72DD9CF55764168FDC147");

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        // 泛型：Post请求
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static T PostResponse<T>(string url, string postData, string contentType = "multipart/form-data") where T : class, new()  //string contentType = "multipart/form-data"
        {
            T result = default(T);

            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
            httpContent.Headers.ContentType.CharSet = "utf-8";
            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    string s = t.Result;
                    //Newtonsoft.Json                   
                    string json = JsonConvert.DeserializeObject(s).ToString();
                    result = JsonConvert.DeserializeObject<T>(json);
                }
            }
            return result;
        }

        public delegate int handleAsync(string str);
        /// <summary>
        /// Http Get Request
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string HttpGetRequest(string url)
        {
            string strGetResponse = string.Empty;
            try
            {
                var getRequest = CreateHttpRequest(url, "GET");
                var getResponse = getRequest.GetResponse() as HttpWebResponse;
                strGetResponse = GetHttpResponse(getResponse, "GET");
            }
            catch (Exception ex)
            {
                strGetResponse = ex.Message;
            }
            return strGetResponse;
        }

        /// <summary>
        /// Http Get Request Async
        /// </summary>
        /// <param name="url"></param>
        public static async void HttpGetRequestAsync(string url)
        {
            string strGetResponse = string.Empty;
            try
            {
                var getRequest = CreateHttpRequest(url, "GET");
                var getResponse = await getRequest.GetResponseAsync() as HttpWebResponse;
                strGetResponse = GetHttpResponse(getResponse, "GET");
            }
            catch (Exception ex)
            {
                strGetResponse = ex.Message;
            }
            Console.WriteLine("reslut:" + strGetResponse);
            //return strGetResponse;
        }

        /// <summary>
        /// Http Post Request
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postJsonData"></param>
        /// <returns></returns>
        public static string HttpPostRequest(string url, string postJsonData)
        {
            string strPostReponse = string.Empty;
            try
            {
                var postRequest = CreateHttpRequest(url, "POST", postJsonData);
                var postResponse = postRequest.GetResponse() as HttpWebResponse;
                strPostReponse = GetHttpResponse(postResponse, "POST");
            }
            catch (Exception ex)
            {
                strPostReponse = ex.Message;
            }
            return strPostReponse;
        }

        /// <summary>
        /// Http Post Request Async
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postJsonData"></param>
        public static async void HttpPostRequestAsync(string url, string postData, handleAsync ha = null)
        {
            string strPostReponse = string.Empty;
            try
            {
                var postRequest = CreateHttpRequest(url, "POST", postData);
                var postResponse = await postRequest.GetResponseAsync() as HttpWebResponse;
                strPostReponse = GetHttpResponse(postResponse, "POST");
            }
            catch (Exception ex)
            {
                strPostReponse = ex.Message;
            }
            if (strPostReponse != "true")
            {
                //Console.WriteLine("--> reslut : " + strPostReponse);
                //Console.WriteLine(postData);

                if (null != ha)
                {
                    ha(strPostReponse);
                }
            }
        }

        public static string HttpUploadFile(string url, int timeOut, string fileKeyName, string filePath, Dictionary<string, string> list)
        {
            string responseContent;
            var memStream = new MemoryStream();
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            // 边界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");//日期的16进制字符串
            // 边界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            // 最后的结束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

            // 设置属性
            webRequest.Method = "POST";
            webRequest.Timeout = timeOut;
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            // 写入文件----------1.--------------
            // 获取文件名称路径最后一级，以\/分级，不分级则取全路径为文件名
            int start = filePath.LastIndexOf("/");
            if (-1 == start)
            {
                start = filePath.LastIndexOf("\\");

                if (-1 == start)
                {
                    start = 0;
                }
            }
            string filename = filePath.Substring(start + 1);
            string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=" + filename + "\r\n" + "Content-Type: application/octet-stream\r\n\r\n";
            var header = string.Format(filePartHeader, fileKeyName, filePath);
            Console.WriteLine(header);

            var headerbytes = Encoding.UTF8.GetBytes(header);
            memStream.Write(beginBoundary, 0, beginBoundary.Length);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            // 获取文件流
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            var buffer = new byte[1024];
            int bytesRead; // =0

            // 文件流写入缓冲区
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }

            // 文件后面要有换行
            string stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
            // 遍历参数，传输数据的编码集----------- 2 -------------------
            foreach (var item in list)
            {   // 
                var dataByte = Encoding.UTF8.GetBytes(string.Format(stringKeyHeader, item.Key, item.Value));
                memStream.Write(dataByte, 0, dataByte.Length);
            }

            // 写入最后的结束边界符------------ 3.-------------------------
            memStream.Write(endBoundary, 0, endBoundary.Length);

            webRequest.ContentLength = memStream.Length;

            var requestStream = webRequest.GetRequestStream();

            memStream.Position = 0;
            var tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();

            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();

            // 响应 ------------------- 4.-----------------------------------
            var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
            {
                responseContent = httpStreamReader.ReadToEnd();
            }

            fileStream.Close();
            httpWebResponse.Close();
            webRequest.Abort();

            return responseContent;
        }

        private static HttpWebRequest CreateHttpRequest(string url, string requestType, string strJson = "")
        {
            HttpWebRequest request = null;

            const string get = "GET";
            const string post = "POST";
            if (string.Equals(requestType, get, StringComparison.OrdinalIgnoreCase))
            {
                request = CreateGetHttpWebRequest(url);
            }
            if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
            {
                request = CreatePostHttpWebRequest(url, strJson);
            }
            return request;
        }

        private static HttpWebRequest CreateGetHttpWebRequest(string url)
        {
            var getRequest = HttpWebRequest.Create(url) as HttpWebRequest;
            getRequest.Method = "GET";
            getRequest.Timeout = 60000;
            getRequest.ContentType = "text/html;charset=UTF-8";
            getRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            return getRequest;
        }

        //utf8编码格式，以免post请求中中文乱码
        private static HttpWebRequest CreatePostHttpWebRequest(string url, string postData)
        {
            System.Net.ServicePointManager.DefaultConnectionLimit = 50;

            byte[] data = Encoding.UTF8.GetBytes(postData);
            var postRequest = HttpWebRequest.Create(url) as HttpWebRequest;
            postRequest.KeepAlive = false;
            postRequest.Timeout = 60000;
            postRequest.Method = "POST";
            postRequest.ContentType = "application/json;charset=UTF-8";
            postRequest.Headers.Add("KeyId", "01ecf5b4-aff9-4221-a4c1-e445f10140d9");

            //   postRequest.UserAgent = initUAString();
            postRequest.ContentLength = data.Length;
            postRequest.AllowWriteStreamBuffering = false;

            //StreamWriter writer = new StreamWriter(postRequest.GetRequestStream(), Encoding.ASCII);

            // 往请求的流里写数据
            using (Stream stream = postRequest.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            //writer.Write(data);
            //writer.Flush();
            return postRequest;
        }

        private static string GetHttpResponse(HttpWebResponse response, string requestType)
        {
            var responseResult = "";
            const string post = "POST";
            string encoding = "UTF-8";
            if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
            {
                encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length < 1)
                {
                    encoding = "UTF-8";
                }
            }
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)))
            {
                responseResult = reader.ReadToEnd();
            }
            return responseResult;
        }

        private static string GetHttpResponseAsync(HttpWebResponse response, string requestType)
        {
            var responseResult = "";
            const string post = "POST";
            string encoding = "UTF-8";
            if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
            {
                encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length < 1)
                {
                    encoding = "UTF-8";
                }
            }
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)))
            {
                responseResult = reader.ReadToEnd();
            }
            return responseResult;
        }

        //dictionary转http get参数
        public static string DictoryToGetParam(Dictionary<string, string> dict)
        {
            string param = "";

            foreach (KeyValuePair<string, string> kv in dict)
            {
                param += kv.Key + '=' + kv.Value + '&';
            }

            if ('&' == param[param.Length - 1])
            {
                param = param.Substring(0, param.Length - 1);
            }

            return param;
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="action"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string PostFile(string action, string file)
        {
            try
            {
                //1、数据边界
                string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                //2、创建HttpWebRequest请求
                HttpWebRequest myRequest = WebRequest.Create(action) as HttpWebRequest;
                myRequest.Method = "POST";
                //3、设置请求ContentType 和 边界字符（边界字符必须和请求数据体的边界字符一致 否则服务器无法解析）
                myRequest.ContentType = "multipart/form-data;boundary=" + boundary;

                //4、添加文件数据描述信息
                StringBuilder sb = new StringBuilder();
                sb.Append("--" + boundary);
                sb.Append("\r\n");
                //name 为 上传文件的input name
                sb.Append("Content-Disposition: form-data; name='MAX_FILE_SIZE'; filename=\"" + file + "\"");
                sb.Append("\r\n");
                sb.Append("Content-Type: application/octet-stream"); //此处则为模拟的文件类型，实际情况下浏览器会根据本地文件后缀名判断此类型
                sb.Append("\r\n\r\n");
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                Encoding encoding = Encoding.GetEncoding("GB2312"); //此处编码须与网页编码一直 否则导致中文路径或文件名乱码 但文件内容不会乱码
                byte[] form_data = encoding.GetBytes(sb.ToString());

                //5、表尾数据
                byte[] foot_data = encoding.GetBytes("\r\n--" + boundary + "--\r\n");


                //6、读取文件
                using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    StringBuilder sb2 = new StringBuilder();
                    sb2.Append("--" + boundary);
                    sb2.Append("\r\n");
                    sb2.Append("Content-Disposition: form-data; name='username';\r\n"); //发送的内容标题
                    sb2.Append("\r\n");
                    sb2.Append("中文名称"); //发送的内容
                    sb2.Append("\r\n"); //每一组数据结束都需要添加换行字符

                    sb2.Append("--" + boundary);
                    sb2.Append("\r\n");
                    sb2.Append("Content-Disposition: form-data; name='pwd';\r\n");
                    sb2.Append("\r\n");
                    sb2.Append("QADSFDSFA");
                    sb2.Append("\r\n");

                    byte[] data = encoding.GetBytes(sb2.ToString());

                    //6、设置上传数据长度为表头 + 文件 + 表尾长度
                    myRequest.ContentLength = form_data.Length + foot_data.Length + fileStream.Length + data.Length;

                    //7、得到请求的数据流
                    Stream requestStream = myRequest.GetRequestStream();
                    //8.1、将字符信息数据写入请求流
                    requestStream.Write(data, 0, data.Length);
                    //8.2、将文件信息数据写入请求流
                    requestStream.Write(form_data, 0, form_data.Length);

                    //9、循环读取文件流 并写入请求流
                    byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }

                    //10、将结束边界数据写入请求流
                    requestStream.Write(foot_data, 0, foot_data.Length);
                }
                //11、发起请求
                HttpWebResponse myResponse = myRequest.GetResponse() as HttpWebResponse;
                //12、读取请求返回的数据流
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), encoding);
                string json = sr.ReadToEnd().Trim();
                return (json);
            }
            catch (Exception e)
            {
                return (e.ToString());
            }

        }
    }
}
